<template>
  <div>
    <h3 v-if="isEdit" class="title">编辑客服</h3>
    <h3 v-else class="title">新增客服</h3>
    <el-form ref="resList" :disabled="formDis" :model="resList" :rules="rules" label-width="100px" class="demo-ruleForm" style="margin-top: 20px;">
      <el-form-item label="客服人姓名" prop="name">
        <el-col :span="6" >
          <el-input v-model="resList.name" maxlength="20" placeholder="请填写客服人姓名" @input="replaceInput(resList.name)"/>
        </el-col>
      </el-form-item>
      <el-form-item label="客服人电话" prop="phone">
        <el-col :span="6" >
          <el-input v-model="resList.phone" :disabled="tinymceDis" type="number" placeholder="请输入手机号码"/>
        </el-col>
      </el-form-item>
      <el-form-item label="微信号" prop="wxNumber">
        <el-col :span="6" >
          <el-input v-model="resList.wxNumber" :disabled="tinymceDis" maxlength="20" type="text" placeholder="请输入微信号"/>
        </el-col>
      </el-form-item>
      <el-form-item label="是否启用" prop="status">
        <el-col :span="6" >
          <el-select v-model="resList.status" :disabled="tinymceDis" placeholder="请选择">
            <el-option :value="'0'" label="停用" />
            <el-option :value="'1'" label="启用" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item v-if="!tinymceDis">
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('resList')">确定</el-button>
        <el-button v-preventReClick v-else type="primary" @click="submitForm('resList')">新增</el-button>
        <el-button v-if="!isEdit" @click="$router.go(-1)">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import config from '@/utils/config';
import { checkPhone, checkIdCard, checkEmail } from '@/utils/regUtil';
import { checkNotEmail, checkNum, checkStudentNum } from '@/utils/validateUtil';
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'
import mixin from '@/mixin'
import { provinceAndCityData, regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { addressAdd, addressUpdate } from '@/api/address'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'));
  } else if (value.toString().length < 6 || value.toString().length > 100) {
    callback(new Error('密码长度为6 - 100个字符'))
  } else {
    callback();
  }
};

const validatephone = (rule, value, callback) => {
  if (!checkPhone(value)) {
    callback(new Error())
  }
  callback()
};
const validateIdCard = (rule, value, callback) => {
  if (!checkIdCard(value)) {
    callback(new Error())
  }
  callback()
};
const validateMail = (rule, value, callback) => {
  if (!checkNotEmail(value)) {
    callback(new Error())
  }
  callback()
};
// const validateNum = (rule, value, callback) => {
//   if (!checkNum(value)) {
//     callback(new Error())
//   }
//   callback()
// };
const validateStudentNum = (rule, value, callback) => {
  if (!checkStudentNum(value)) {
    callback(new Error())
  }
  callback()
};

const validateStudentNumber = (rule, value, callback) => {
  if (value.length > 5) {
    callback(new Error())
  }
  callback()
};

const validateZero = (rule, value, callback) => {
  if (!checkNum(value)) {
    callback(new Error())
  }
  callback()
};

export default {
  components: { Tinymce },
  mixins: [mixin],
  data() {
    return {
      userName: '',
      options: regionData,
      cityCode: [],
      resList: {
        name: '',
        status: '0',
        phone: '',
        wxNumber: ''
      },
      rules: {
        name: [
          { required: true, message: '请填写姓名', trigger: 'blur' },
          { pattern: /^[A-z0-9\u4e00-\u9fa5]*$/, message: '不能含有特殊字符', trigger: 'blur' }
        //   { max: 50, message: '输入字符不得超过50个', trigger: 'blur' }
          // { pattern: /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, message: '不能含有特殊字符', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择是否启用', trigger: 'blur' }
          // { max: 100, message: '输入字符不得超过100个', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatephone, message: '请输入正确的手机号码', trigger: 'blur' }
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          // { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        wxNumber: [
          { required: true, message: '请输入微信号', trigger: 'blur' }
          // { validator: validateNum, message: '请输入数字', trigger: 'blur' },
          // { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      },
      isEdit: false,
      fileList: [],
      uploadData: {
        key: '',
        token: ''
      },
      formDis: false,
      tinymceDis: false,

      selectShow: false,
      // 对应<请选择讲师下拉菜单>查询教师信息列表时，把status为1的教师获取出来
      // 选择今天以后的日期
      //   pickerOptions: {
      //     disabledDate(time) {
      //       return time.getTime() < Date.now() - 8.64e7;
      //     }
      //   },
      isDisabled: false
    }
  },
  computed: {
    ruleForm: function() {
      return this.$store.getters.ruleForm
    }
  },
  watch: {
    // ruleForm: {
    //   handler: function(nowVal, oldVal) {
    //     this.$store.dispatch('AddlistenForm', this.ruleForm).then(() => {
    //     }).catch((err) => {
    //       Message.error(err.err)
    //     })
    //   },
    //   deep: true
    // }
  },
  created() {
    this.userName = getLocalUserName()
    if (this.userName !== 'admin') this.tinymceDis = true
  },
  mounted() {
    const _self = this;
    // console.log('this.$route.query:', JSON.stringify(this.$route.query))
    // console.log(JSON.parse(_self.$route.query.isEdit))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? JSON.parse(_self.$route.query.isEdit) : false;
      // 如果是编辑页面，把路由参数带给resList
      this.resList = this.$route.query
      // if (this.resList.province) this.cityCode[0] = this.resList.province
      this.cityCode = [this.resList.province, this.resList.city, this.resList.county]
      // 并且把isEdit（不相关参数）去掉
      // delete this.resList.isEdit;
      if (this.isEdit) {
        const a = this.$route.query
        this.resList = a.data
        this.cityCode = [this.resList.province, this.resList.city, this.resList.county]
      }
    }

    // if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
    //   // this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
    //   //   this.formDis = Boolean(this.$route.query.isLook)
    //   //   this.tinymceDis = Boolean(this.$route.query.isLook)
    //   // const a = this.$route.query
    //   //   if (a.hasOwnProperty('isLook')) {
    //   //     this.dataToHtml(a)
    //   //     this.selectShow = true
    //   //     delete a.isLook;
    //   //   }
    //   //   if (a.hasOwnProperty('isEdit')) {
    //   //     this.dataToHtml(a)
    //   //     this.getTeacherList()
    //   //     delete a.isEdit;
    //   //   }
    // //   this.$store.dispatch('AddlistenForm', this.$route.query).then(() => {
    // //   }).catch((err) => {
    // //     Message.error(err.err)
    // //   })
    // } else { // 新增
    // //   this.getTeacherList()
    // //   this.$store.dispatch('resetFunc').then(() => {
    // //   }).catch((err) => {
    // //     Message.error(err.err)
    // //   })
    // }
    // this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    replaceInput(value) {
      this.resList.name = this.validForbid(value)
    },
    resetForm(formName) {
      this.resList = {
        name: '',
        gender: '',
        phone: '',
        wxNumber: ''
      }
      this.cityCode = []
      this.options = regionData
    },
    // 省市
    handleChange(value) {
      // this.tRuleForm.province = value[0] // CodeToText[value[0]]
      // this.tRuleForm.city = value[1] // CodeToText[value[1]]
      //  this.resList.province = CodeToText[value[0]]
      //  this.resList.city = CodeToText[value[1]]
      // this.resList.city = [CodeToText[value[0]], CodeToText[value[1]], CodeToText[value[2]]]
      // this.resList.city = [value[0], value[1], value[2]]
      this.resList.province = value[0]
      this.resList.city = value[1]
      this.resList.county = value[2]
      //  console.log('1:', this.resList.province, this.resList.city)
      console.log(this.resList.province, this.resList.city, this.resList.county)
    },
    request(data) {
      if (this.isEdit) { // 编辑
        console.log('1-->', data)
        // 因姓名不能修改， 传参时去掉名字字段
        // delete data.name
        // 去掉创建时间字段
        // delete data.createTime
        console.log('2-->', data)
        this.loading = true
        addressUpdate(data).then(response => {
          console.log(data)
          if (Number(response.code) === 200) {
            Message.success('编辑成功')
            this.$router.push('list');
          } else {
            Message.error(response.message + '-' + response.data)
          }
        })
      } else { // 新增
        this.$router.push('list')
        addressAdd(data).then(response => {
          console.log('正在新增')
          if (Number(response.code) === 200) {
            Message.success('新增成功')
            this.$router.push('list');
          } else {
            Message.error(response.message + '-' + response.data)
          }
        });
      }
    },
    // dataToHtml(query) {
    //   query.cPlan = this.changeToHtml(query.cPlan)
    //   query.costDesc = this.changeToHtml(query.costDesc)
    //   query.precautions = this.changeToHtml(query.precautions)
    // },
    // dataToCode(data) {
    //   data.cPlan = this.changeToCode(data.cPlan)
    //   data.costDesc = this.changeToCode(data.costDesc)
    //   data.precautions = this.changeToCode(data.precautions)
    // },
    // changeToCode(str) {
    //   return str.replace(/\r\n|\r|\n/g, '<br/>')
    // },
    // changeToHtml(str) {
    //   return str.replace(/<br\s*\/?>/g, '\n')
    // },
    // getTeacherList() {
    //   getTeacherList(this.listQuery).then(response => {
    //     this.teacher = response.data.list
    //     console.log(this.teacher.length)
    //     this.selectShow = true
    //   })
    // },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.resList)
          this.request(this.resList)
        } else {
          this.validateError()
          return false;
        }
      });
    }
    //   this.$store.dispatch('resetFunc').then(() => {
    //   }).catch((err) => {
    //     Message.error(err.err)
    //   })
  }
}
</script>

<style scoped>
.el-select,.el-cascader{
    display: block !important;
}
.title{
    margin-left: 20px;
}
  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }
</style>
